// 洛谷P2123 皇后游戏 贪心算法
#include <iostream>
#include <algorithm>
using namespace std;
class node {
    public:
    int x, y, d;
    bool operator <(node a) const {
        if(this->d!=a.d)return d<a.d;
        if(d<=0)return this->x<a.x;
        else return this->y>a.y;
    }
    void calcd(){
        if(x<y)d=-1;
        else if(x>y)d=1;
        else d=0;
    }
};

int main() {
    int t;
    cin >> t;
    node a[20005];
    long long c[20005];
    for(int i=0;i<t;i++){
        int n;
        cin >> n;
        for(int j=1;j<=n;j++){
            cin >> a[j].x >> a[j].y;
            a[j].calcd();
        }
        sort(a+1, a+n+1);
        long long s=0;
        for(int j=1;j<=n;j++){
            s+=(long long)a[j].x;
            c[j] = max(c[j-1], s) + a[j].y;
        }
        cout<<c[n]<<endl;
    }

    return 0;
}